package com.znzz.controller;

import com.znzz.entity.News;
import com.znzz.service.NewsService;
import com.znzz.utils.DateUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping(path = "/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @RequestMapping(path = "/uploadImage", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public HashMap uploadImage(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {

////        String path = System.getProperty("user.dir") + "/saveImages/";
//        String path = "F:/SSM小项目/ssm_pageTest" + "/saveImages/";
//        System.out.println("path:" + path);
//        Calendar instance = Calendar.getInstance();
//        String month = (instance.get(Calendar.MONTH) + 1) + "月";
//        path = path + month;
//        File realFile = new File(path);
//        if (!realFile.exists()) {
//            realFile.mkdir();
//        }
//        String originalFileName= file.getOriginalFilename();
//
//        UUID uuid = UUID.randomUUID();
//        //生成的uuid中有-，需要使用空字符串替换掉，再把太长生成的随机数割掉
//        String id = uuid.toString().replace("-", "").substring(27);
//        //使用下划线将生成的uuid与文件名拼接起来
//        String uniqueFileName = id + "_" + originalFileName;
//        System.out.println("uniqueFileName:" + uniqueFileName);
//        File saveFile = new File(path, uniqueFileName);
//
//        file.transferTo(saveFile);
//
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("url", "/saveImages/"+month + "/"+uniqueFileName);
//        jsonObject.put("success", 1);
//        jsonObject.put("message", "upload success!");
//
//        System.out.println(jsonObject);
//
//        return jsonObject;


        //获得SpringBoot当前项目的路径：System.getProperty("user.dir")
        String path = "F:/SSM小项目/ssm_pageTest" + "/saveImages/";

//        String path = System.getProperty("user.dir")+"/saveImages/";
        System.out.println("path:" + path);
        //按照月份进行分类：
        Calendar instance = Calendar.getInstance();
//        String month = (instance.get(Calendar.MONTH) + 1) + "月";
        String month = (instance.get(Calendar.MONTH) + 1)+"";
        path = path + month;
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
        //上传文件地址
        System.out.println("上传文件保存地址：" + realPath);

        //解决文件名字问题：我们使用uuid;
        String filename = "ks-" + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(new File(realPath + "/" + filename));

        //给editormd进行回调
        HashMap res = new HashMap();
//        res.put("url", request.getContextPath()+"/saveImages/" + month + "/" + filename);
        res.put("url","/saveImages/" + month + "/" + filename);
        res.put("success", 1);
        res.put("message", "upload success!");
        System.out.println(res);
        return res;


    }

    @PostMapping(path = "/sendNews")
    public String sendNews(News news){
        news.setCreateTime(DateUtil.SimpleDateFormat(new Date()));
        int flag=newsService.addNews(news);
        if(flag==1){
            System.out.println(news.getNewsArticle());
            System.out.println("成功了");
            return "sendSucceed";
        }else{
            System.out.println("失败了");
            return "sendFailed";
        }

    }

    @RequestMapping(path = "/showNews")
    public ModelAndView showNews(ModelAndView mv, ModelMap modelMap, @RequestParam(value = "start",defaultValue = "1") Integer pageStart, @RequestParam(value = "size",defaultValue = "10") Integer pageSize){
        int count=newsService.countAllNews();
        List<News> newsList=newsService.findAllNews(pageStart,pageSize);
        Map<String,Object> map= new HashMap<>();
        map.put("newsList",newsList);
        map.put("count",count);
        map.put("curr",pageStart);
        modelMap.addAllAttributes(map);

        mv.setViewName("admin/showNews");
        return mv;
    }

//    @RequestMapping(path = "/queryNews" ,method = RequestMethod.POST)
//    public String queryNews(@RequestParam(value = "keys") String keys){
//       Map<String,Object> map= new HashMap<>();
//
//       newsService.queryNewsByCondition(map);
//
//    }

    @RequestMapping(path = "/showDetails")
    public ModelAndView showDetails(@RequestParam(name = "id") Integer id, ModelAndView mv){

        News news=newsService.findById(id);
        mv.addObject("news",news);
        mv.setViewName("newsDetail");
        return mv;

    }

    @RequestMapping(path = "/deleteNews")
    public void deleteNewsById(@RequestParam(name = "id") Integer id, HttpServletResponse response,HttpServletRequest request) throws IOException, ServletException {

        if(newsService.deleteNews(id)){
            response.sendRedirect(request.getContextPath()+"/news/showNews");
        }else{
            System.out.println("执行失败");
            request.getRequestDispatcher("/WEB-INF/pages/sendFailed.jsp").forward(request, response);
        }

    }

    @RequestMapping(path = "/reviseNews")
    public String reviseNews(@RequestParam(name = "id") Integer id,Model model){
        News news=newsService.findById(id);
        model.addAttribute("news",news);
        return "admin/update_news";
    }


    @RequestMapping(path = "/updateNews")
    public String updateNews(News news){
        news.setCreateTime(DateUtil.SimpleDateFormat(new Date()));
        System.out.println(news.getId());
        if(newsService.updateNews(news)){
            return "redirect:/news/showNews";
        }else{
            System.out.println("修改失败");
            return "";
        }

    }




}
